// pages/msg_canvas/msg_canvas.js
let app = getApp();
var QRCode = require('../../utils/weapp-qrcode.js');
var tsc = require("../../utils/tsc.js");
var esc = require("../../utils/esc.js");
var encode = require("../../utils/encoding.js");
var qrcode = null;
var code = ''
var quality = 1
Page({

    /**
     * 页面的初始数据
     */
    data: {
        sendContent: "",
        looptime: 0,
        currentTime: 1,
        lastData: 0,
        oneTimeData: 0,
        returnResult: "",
        canvasWidth: 80,
        canvasHeight: 80,
        buffSize: [],
        buffIndex: 0,
        printNum: [],
        printNumIndex: 0,
        printerNum: 1,
        currentPrint: 1,
        isReceiptSend: false,
        isLabelSend: false,
        list: [],
        services: [],
        serviceId: 0,
        writeCharacter: false,
        readCharacter: false,
        notifyCharacter: false,
        isScanning: false,
        istrue: true,
        imgsrc: []
    },
    Forward(e){
        console.log(222222)
        wx.previewImage({
            current: this.data.imgsrc[0], // 当前显示图片的http链接
            urls: this.data.imgsrc // 需要预览的图片http链接列表
        })
    },
    // 长按保存
    save: function () {
        console.log('save')
        wx.showActionSheet({
            itemList: ['保存图片'],
            success: function (res) {
                console.log(res.tapIndex)
                if (res.tapIndex == 0) {
                    qrcode.exportImage(function (path) {
                        wx.saveImageToPhotosAlbum({
                            filePath: path,
                        })
                    })
                }
            }
        })
    },
    startSearch: function () { // 打开蓝牙
        var that = this
        wx.openBluetoothAdapter({
            success: function (res) {
                wx.getBluetoothAdapterState({
                    success: function (res) {
                        if (res.available) {
                            if (res.discovering) {
                                wx.stopBluetoothDevicesDiscovery({
                                    success: function (res) {
                                        console.log(res)
                                    }
                                })
                            }
                            that.checkPemission()
                        } else {
                            wx.showModal({
                                title: '提示',
                                content: '本机蓝牙不可用',
                            })
                        }
                    },
                })
            },
            fail: function () {
                wx.showModal({
                    title: '提示',
                    content: '蓝牙初始化失败，请打开蓝牙',
                })
            }
        })
    },
    checkPemission: function () { //android 6.0以上需授权地理位置权限
        var that = this
        var platform = app.globalData.platform
        if (platform == "ios") {
            app.globalData.platform = "ios"
            that.getBluetoothDevices()
        } else if (platform == "android") {
            app.globalData.platform = "android"
            console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1))
            if (app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1) > 5) {
                wx.getSetting({
                    success: function (res) {
                        console.log(res)
                        if (!res.authSetting['scope.userLocation']) {
                            wx.authorize({
                                scope: 'scope.userLocation',
                                complete: function (res) {
                                    that.getBluetoothDevices()
                                }
                            })
                        } else {
                            that.getBluetoothDevices()
                        }
                    }
                })
            }
        }
    },
    getBluetoothDevices: function () { //获取蓝牙设备信息
        var that = this
        console.log("start search")
        wx.showLoading({
            title: '正在加载',
        })
        that.setData({
            isScanning: true
        })
        wx.startBluetoothDevicesDiscovery({
            success: function (res) {
                console.log(res)
                setTimeout(function () {
                    wx.getBluetoothDevices({
                        success: function (res) {
                            var devices = []
                            var num = 0
                            for (var i = 0; i < res.devices.length; ++i) {
                                if (res.devices[i].name != "未知设备") {
                                    devices[num] = res.devices[i]
                                    num++
                                }
                            }
                            console.log(555555555555)
                            console.log(devices)
                            that.setData({
                                list: devices,
                                isScanning: false
                            })
                            wx.hideLoading()
                            wx.stopPullDownRefresh()
                        },
                    })
                }, 3000)
            },
        })
    },
    bindViewTap: function (e) {
        var that = this
        wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
                console.log(res)
            },
        })
        that.setData({
            serviceId: 0,
            writeCharacter: false,
            readCharacter: false,
            notifyCharacter: false
        })
        console.log(e.currentTarget.dataset.title)
        wx.showLoading({
            title: '正在连接',
        })
        wx.createBLEConnection({
            deviceId: e.currentTarget.dataset.title,
            success: function (res) {
                console.log(res)
                app.globalData.deviceId = e.currentTarget.dataset.title
                that.getSeviceId()
            },
            fail: function (e) {
                wx.showModal({
                    title: '提示',
                    content: '连接失败',
                })
                console.log(e)
                wx.hideLoading()
            },
            complete: function (e) {
                console.log(e)
            }
        })
    },
    getSeviceId: function () {
        var that = this
        var platform = app.globalData.platform
        console.log(app.globalData.deviceId)
        wx.getBLEDeviceServices({
            deviceId: app.globalData.deviceId,
            success: function (res) {
                console.log(res)
                // var realId = ''
                // if (platform == 'android') {
                //   // for(var i=0;i<res.services.length;++i){
                //   // var item = res.services[i].uuid
                //   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
                //   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
                //   //       break;
                //   //     }
                //   // }
                // } else if (platform == 'ios') {
                //   // for(var i=0;i<res.services.length;++i){
                //   // var item = res.services[i].uuid
                //   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
                //   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
                //   // break
                //   // }
                //   // }
                // }
                // app.globalData.serviceId = realId
                that.setData({
                    services: res.services
                })
                that.getCharacteristics()
            },
            fail: function (e) {
                console.log(e)
            },
            complete: function (e) {
                console.log(e)
            }
        })
    },
    getCharacteristics: function () {
        var that = this
        var list = that.data.services
        var num = that.data.serviceId
        var write = that.data.writeCharacter
        var read = that.data.readCharacter
        var notify = that.data.notifyCharacter
        wx.getBLEDeviceCharacteristics({
            deviceId: app.globalData.deviceId,
            serviceId: list[num].uuid,
            success: function (res) {
                console.log(res)
                for (var i = 0; i < res.characteristics.length; ++i) {
                    var properties = res.characteristics[i].properties
                    var item = res.characteristics[i].uuid
                    if (!notify) {
                        if (properties.notify) {
                            app.globalData.notifyCharaterId = item
                            app.globalData.notifyServiceId = list[num].uuid
                            notify = true
                        }
                    }
                    if (!write) {
                        if (properties.write) {
                            app.globalData.writeCharaterId = item
                            app.globalData.writeServiceId = list[num].uuid
                            write = true
                        }
                    }
                    if (!read) {
                        if (properties.read) {
                            app.globalData.readCharaterId = item
                            app.globalData.readServiceId = list[num].uuid
                            read = true
                        }
                    }
                }
                if (!write || !notify || !read) {
                    num++
                    that.setData({
                        writeCharacter: write,
                        readCharacter: read,
                        notifyCharacter: notify,
                        serviceId: num
                    })
                    if (num == list.length) {
                        wx.showModal({
                            title: '提示',
                            content: '找不到该读写的特征值',
                        })
                    } else {
                        that.getCharacteristics()
                    }
                } else {
                    // that.labelTest()
                    that.openControl()
                }
            },
            fail: function (e) {
                console.log(e)
            },
            complete: function (e) {
                console.log("write:" + app.globalData.writeCharaterId)
                console.log("read:" + app.globalData.readCharaterId)
                console.log("notify:" + app.globalData.notifyCharaterId)
            }
        })
    },
    
    
    openControl: function () {
        wx.navigateTo({
          url: '../msg_sendCommand/msg_sendCommand?code=' + code,
        })
      },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this
        app.globalData.platform = app.getPlatform()
        code = options.code
        wx.getSystemInfo({
            success: function (res) {
                console.log(res.windowWidth);
                console.log(res.windowHeight);
                that.setData({
                    windowWidth: res.windowWidth,
                    windowHeight: res.windowHeight
                })
            },
        })
        qrcode = new QRCode('canvas', {
            usingIn: this, // usingIn 如果放到组件里使用需要加这个参数
            // text: "https://github.com/tomfriwel/weapp-qrcode",
            // image: '/images/bg.jpg',
            width: that.data.windowWidth / 100 * 60,
            height: that.data.windowHeight / 100 * 40,
            colorDark: "lightblue",
            colorLight: "#ffffff",
            autoColor: true,
            correctLevel: QRCode.CorrectLevel.H,
        });
        // 生成图片，绘制完成后调用回调
        qrcode.makeCode(code, () => {
            // 回调
            setTimeout(() => {
                qrcode.exportImage(function (path) {
                    that.data.imgsrc.push(path)
                    that.data.imgsrc.push(path)
                    that.setData({
                        imgsrc: that.data.imgsrc,
                        istrue: false,
                    })
                    console.log(that.data.imgsrc)
                    // wx.previewImage({
                    //     current: that.data.imgsrc[0], // 当前显示图片的http链接
                    //     urls: that.data.imgsrc // 需要预览的图片http链接列表
                    // })
                })
            }, 200)
        })
       
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
       
    },
  

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.closeBLEConnection({
            deviceId: app.globalData.deviceId,
            success: function (res) {
                console.log("关闭蓝牙成功")
            },
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})